package com.qiyadeng.wechat.web;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.util.Date;
import java.util.List;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mobile.device.Device;
import org.springframework.mobile.device.site.SitePreference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.base.Strings;
import com.qiyadeng.company.biz.Card;
import com.qiyadeng.company.biz.Information;
import com.qiyadeng.company.biz.MmtService;
import com.qiyadeng.company.biz.ResSelectUser;
import com.qiyadeng.company.biz.RespGrantTicket;
import com.qiyadeng.company.biz.TicketGrant;
import com.qiyadeng.wechat.baidu.BaiduGeoCodeResponse;
import com.qiyadeng.wechat.baidu.BaiduMapService;
import com.qiyadeng.wechat.baidu.BaiduPlaceResponse;
import com.qiyadeng.wechat.baidu.GeoUtil;
import com.qiyadeng.wechat.baidu.GeoUtil.GaussSphere;
import com.qiyadeng.wechat.config.WeChatConstant;
import com.qiyadeng.wechat.model.WeChatEventMessage;
import com.qiyadeng.wechat.model.WeChatLocationMessage;
import com.qiyadeng.wechat.model.WeChatReplyNewsMessage;
import com.qiyadeng.wechat.model.WeChatReplyTextMessage;
import com.qiyadeng.wechat.model.WeChatTextMessage;
import com.qiyadeng.wechat.roo.model.Article;
import com.qiyadeng.wechat.roo.model.Catalog;
import com.qiyadeng.wechat.roo.model.MessageRecord;
import com.qiyadeng.wechat.roo.model.ProWechat;
import com.qiyadeng.wechat.roo.model.Prod;
import com.qiyadeng.wechat.roo.model.Store;
import com.qiyadeng.wechat.roo.model.StoreArea;
import com.qiyadeng.wechat.roo.model.UserBinding;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
//@RequestMapping("/wechat/**")
@Controller
public class WeChatController {

	private Logger logger = LoggerFactory.getLogger(WeChatController.class);
	
    @RequestMapping(value="/wechat/",method = RequestMethod.POST)
    @ResponseBody
    public String post(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) throws IOException {
    	response.setContentType("text/html;charset=UTF-8");
    	String wxMsgXml = IOUtils.toString(request.getInputStream(),"utf-8");
		logger.debug(" get wechat message "+ wxMsgXml);
		MessageRecord mr = new MessageRecord();
		mr.setXmlQuestion(wxMsgXml);
		mr.persist();
		String type = "text";
		
		StringBuffer sss = new StringBuffer();
		sss.append(WeChatConstant.FOLLOW_MESSAGE);
		
		
		if(wxMsgXml.indexOf("<MsgType><![CDATA[text]]></MsgType>")>0) {
			type = "text";
		}
		else if(wxMsgXml.indexOf("<MsgType><![CDATA[location]]></MsgType>")>0) {
			type = "location";
		}
		else if(wxMsgXml.indexOf("<MsgType><![CDATA[voice]]></MsgType>")>0) {
			type ="voice";
		}
		else if(wxMsgXml.indexOf("<MsgType><![CDATA[event]]></MsgType>")>0) {
			type ="event";
		}
		else{
			type = "unknown";
		}
		StringBuffer replyMsg = new StringBuffer();
		String returnXml = "";
		WeChatTextMessage textMsg = null;
		//text message
		if("text".equalsIgnoreCase(type)){
			textMsg = getWeChatTextMessage(wxMsgXml);
			
			//先判断整数
			if(textMsg != null && !Strings.isNullOrEmpty(textMsg.getContent())){
				Integer index = -1;
				try {
					index = Integer.parseInt(textMsg.getContent());
				} catch (NumberFormatException e) {
					e.printStackTrace();
				}
				if(index > 0){//整数
					if(index == 1){//用户注册
						returnXml = getReplyTextMessage("注册新帐户,"+"<a href='"+WeChatConstant.BASE_PIC_WEBSITE+"/wechat/register/?wechatuser="+textMsg.getFromUserName()+"'>"+"点击注册"+"</a>", textMsg.getFromUserName());
						return returnXml;
					}
					else if (index == 2){//会员卡绑定
						returnXml = getReplyTextMessage("请先进行绑定,"+"<a href='"+WeChatConstant.BASE_PIC_WEBSITE+"/wechat/mobile/?wechatuser="+textMsg.getFromUserName()+"'>"+"点击绑定"+"</a>", textMsg.getFromUserName());
						return returnXml;
					}
					else if (index ==3){//积分查询
						UserBinding ub = UserBinding.getUserBindingByWeChatId(textMsg.getFromUserName());
						if(ub == null){
							returnXml = getReplyTextMessage("请先进行绑定,"+"<a href='"+WeChatConstant.BASE_PIC_WEBSITE+"/wechat/mobile/?wechatuser="+textMsg.getFromUserName()+"'>"+"点击绑定"+"</a>", textMsg.getFromUserName());
							return returnXml;
						}
						MmtService mmt = new MmtService();
						ResSelectUser rsu = mmt.selectUserInfo("", "", ub.getPhone(), "");
						if(rsu != null){
							List<Card> cards = rsu.getInformation().getCardlist();
							if(cards.size()> 0){
								String score = mmt.getCardIntegral(cards.get(0).getCardno(), "");
								returnXml = getReplyTextMessage(WeChatConstant.SCORE_HINT + score, textMsg.getFromUserName());
								return returnXml;
							}
						}
					}
					else if (index ==4){//会员卡修改密码
						returnXml = getReplyTextMessage(WeChatConstant.MODIFY_CARD_PASSWORD+"<a href='"+WeChatConstant.BASE_PIC_WEBSITE+"/wechat/gomodify/?wechatuser="+textMsg.getFromUserName()+"'>"+"点击修改卡密码"+"</a>", textMsg.getFromUserName());
						return returnXml;
					}
					else if (index ==5){//问卷有礼
						returnXml = getReplyTextMessage("邀请您参加问卷调查,"+"<a href='"+WeChatConstant.Survey_ADDRESS+"?wechatuser="+textMsg.getFromUserName()+"'>"+"点击参加"+"</a>", textMsg.getFromUserName());
						return returnXml;
					}
					else if (index ==6){//产品明细
						returnXml = getReplyTextMessage(WeChatConstant.PRODUCT_HINT, textMsg.getFromUserName());
						return returnXml;
					}
					else if (index ==7){//当月促销活动
						List<ProWechat> proList = ProWechat.getLastestPromotion();
						if(proList!=null&&proList.size()>0){
							return getProWeChat(proList, textMsg.getContent(), textMsg.getFromUserName());
						}
					}
					else if (index ==8){//公司介绍
						returnXml = getReplyTextMessage(WeChatConstant.COMPANY_INTRO+"<a href='"+WeChatConstant.BASE_PIC_WEBSITE+"/wechat/company/?wechatuser="+textMsg.getFromUserName()+"'>"+"点击查看更多"+"</a>", textMsg.getFromUserName());
						return returnXml;
					}
					else if (index ==9){//门店查询
						returnXml = getReplyTextMessage(WeChatConstant.STORE_HINT, textMsg.getFromUserName());
						return returnXml;
					}
					else if (index ==10) {//新品推荐
						List<ProWechat> proList = ProWechat.findProWechatsByNameAndDesc("新品");
						if(proList!=null&&proList.size()>0){
							return getProWeChat(proList, "新品", textMsg.getFromUserName());
						}
					}
				}
			}
			
			
			//用户绑定
			if(textMsg.getContent().indexOf("绑定")>-1){
				returnXml = getReplyTextMessage("请先进行绑定,"+"<a href='"+WeChatConstant.BASE_PIC_WEBSITE+"/wechat/mobile/?wechatuser="+textMsg.getFromUserName()+"'>"+"点击绑定"+"</a>", textMsg.getFromUserName());
				return returnXml;
			}
			
			//注册
			if(textMsg.getContent().indexOf("注册")>-1){
				returnXml = getReplyTextMessage("注册新帐户,"+"<a href='"+WeChatConstant.BASE_PIC_WEBSITE+"/wechat/register/?wechatuser="+textMsg.getFromUserName()+"'>"+"点击注册"+"</a>", textMsg.getFromUserName());
				return returnXml;
			}
			
			//公司介绍
			if(textMsg.getContent().indexOf("公司介绍")>-1||textMsg.getContent().indexOf("介绍")>-1){
				returnXml = getReplyTextMessage(WeChatConstant.COMPANY_INTRO+"<a href='"+WeChatConstant.BASE_PIC_WEBSITE+"/wechat/company/?wechatuser="+textMsg.getFromUserName()+"'>"+"点击查看更多"+"</a>", textMsg.getFromUserName());
				return returnXml;
			}
			
			//最新活动
			if(textMsg.getContent().indexOf("最新活动")>-1||textMsg.getContent().indexOf("活动")>-1){
				List<ProWechat> proList = ProWechat.getLastestPromotion();
				if(proList!=null&&proList.size()>0){
					return getProWeChat(proList, textMsg.getContent(), textMsg.getFromUserName());
				}
			}
			
			//产品信息搜索
			List<ProWechat> proList = ProWechat.findProWechatsByNameAndDesc(textMsg.getContent());
			if(proList!=null&&proList.size()>0){
				return getProWeChat(proList, textMsg.getContent(), textMsg.getFromUserName());
			}
			
			//余额查询
			if(textMsg.getContent().indexOf("余额")>-1){
				/*
				BizAccountService bizAccountService = new BizAccountService();
				double myMoney = bizAccountService.getMyMoney(textMsg.getFromUserName());
				returnXml = getReplyTextMessage("余额为："+myMoney, textMsg.getFromUserName());
				return returnXml;
				*/
				UserBinding ub = UserBinding.getUserBindingByWeChatId(textMsg.getFromUserName());
				if(ub == null){
					returnXml = getReplyTextMessage("请先进行绑定,"+"<a href='"+WeChatConstant.BASE_PIC_WEBSITE+"/wechat/mobile/?wechatuser="+textMsg.getFromUserName()+"'>"+"点击绑定"+"</a>", textMsg.getFromUserName());
					return returnXml;
				}
				MmtService mmt = new MmtService();
				ResSelectUser rsu = mmt.selectUserInfo("", "", ub.getPhone(), "");
				Information inf = rsu.getInformation();
				List<Card> cards = rsu.getInformation().getCardlist();
				
			}
			
			//优惠券查询
			if(textMsg.getContent().indexOf("优惠券")>-1){
				UserBinding ub = UserBinding.getUserBindingByWeChatId(textMsg.getFromUserName());
				if(ub == null){
					returnXml = getReplyTextMessage("请先进行绑定,"+"<a href='"+WeChatConstant.BASE_PIC_WEBSITE+"/wechat/mobile/?wechatuser="+textMsg.getFromUserName()+"'>"+"点击绑定"+"</a>", textMsg.getFromUserName());
					return returnXml;
				}
				MmtService mmt = new MmtService();
				ResSelectUser rsu = mmt.selectUserInfo("", "", ub.getPhone(), "");
				//查询你的所有优惠券
				
			}
			
			//问卷调查
			if(textMsg.getContent().indexOf("问卷")>-1||textMsg.getContent().indexOf("调查")>-1){
				returnXml = getReplyTextMessage("邀请您参加问卷调查,"+"<a href='"+WeChatConstant.Survey_ADDRESS+"?wechatuser="+textMsg.getFromUserName()+"'>"+"点击参加"+"</a>", textMsg.getFromUserName());
				return returnXml;
			}
			
			//建议咨询
			
			//天气预报
			//http://api.easyon.cn:8080/weather-web/GetWeatherInfoFromCityName.action?cityName=hangzhou
			
			
			//检查是不是位置信息
			BaiduMapService baidu = new BaiduMapService();
			BaiduGeoCodeResponse geo = null;
			try {
				geo = BaiduGeoCodeResponse.getBaiduGeoCode(baidu.getGeoCode(textMsg.getContent()));
			} catch (Exception e) {
				logger.warn(e.getMessage());
			}
			logger.info("geo="+geo.toString());
			if(geo!= null&&geo.getLat()!=null&&geo.getLng()!=null&&geo.getLat().length()>0&&geo.getLng().length()>0){
				//returnXml = getLocMsg(geo.getLat(),geo.getLng(),textMsg.getFromUserName());
				returnXml = getStores(geo.getLat(),geo.getLng(),textMsg.getFromUserName());
			}
			else{
				if(textMsg != null){
					
					replyMsg.append(sss);
					returnXml = getReplyTextMessage(replyMsg.toString(), textMsg.getFromUserName());
				}
			}
		}
		//location message
		else if("location".equalsIgnoreCase(type)){
			WeChatLocationMessage localMsg = WeChatLocationMessage.getWeChatLocationMessage(wxMsgXml);
			//returnXml = getLocMsg(localMsg.getLocationx(),localMsg.getLocaltiony(),localMsg.getFromUserName());
			returnXml = getStores(localMsg.getLocationx(),localMsg.getLocaltiony(),localMsg.getFromUserName());
		}
		
		//event message 事件
		else if("event".equalsIgnoreCase(type)){
			WeChatEventMessage weChatEventMessage =  getWeChatEventMessage(wxMsgXml);
			if ("subscribe".equalsIgnoreCase(weChatEventMessage.getEvent())) {
				replyMsg.append(sss);
				returnXml = getReplyTextMessage(replyMsg.toString(), weChatEventMessage.getFromUserName());
			}
			else if ("unsubscribe".equalsIgnoreCase(weChatEventMessage.getEvent())) {
				replyMsg.append("谢谢您的关注。");
				returnXml = getReplyTextMessage(replyMsg.toString(), weChatEventMessage.getFromUserName());				
			}

		}
		
		//unknown type
		else{
			//TODO 通过正则表达式，确认消息发送者ID。
			//replyMsg.append(":)不是文本的消息，我暂时看不懂");
			//returnXml = getReplyTextMessage(replyMsg.toString(), textMsg.getFromUserName());
		}
		logger.debug("reply message "+ returnXml);
		mr.setXmlAnswer(returnXml);
		mr.persist();
		return returnXml;
    }

    @RequestMapping(value="/wechat/",method=RequestMethod.GET)
    @ResponseBody
    public String index(String echostr, Model model) {
		String echo = "";
		try {
			echo = new String(echostr.getBytes("ISO-8859-1"),"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		logger.info("check message from wechat:"+ echo);
		return echo;
    }
    
    //调查完成之后的送券页面
    @RequestMapping(value="/wechat/coupon/",method=RequestMethod.GET)
    public String givenCoupon( Model model,HttpServletRequest request){
    	String wechatuser = request.getParameter("wechatuser");
    	logger.info("coupon wechatuser : " + wechatuser);
    	
    	if(wechatuser!= null && wechatuser.length()==11){
    		//手机
    		MmtService sms = new MmtService("");
    		MmtService mmt = new MmtService();
    		RespGrantTicket ticket = mmt.grantTicket(wechatuser);
    		TicketGrant tg= ticket.getTickets().get(0);
    		if(tg != null){
    			//String smsStr = String.format(WeChatConstant.GIVEN_COUPON_MSG, tg.getTicketName(),tg.getTicketNo());
    			String smsStr =  MessageFormat.format(WeChatConstant.GIVEN_COUPON_MSG, tg.getTicketNo());
    			sms.sendSms(wechatuser, smsStr);
    			model.addAttribute("code","成功");
    			model.addAttribute("reason",smsStr);
    		}
    		else {
    			model.addAttribute("code","失败");
    			model.addAttribute("reason","发券失败。");
			}
    	}
    	else if (wechatuser!= null && wechatuser.length() > 11){
    		//微信号码
    		UserBinding userBind = UserBinding.getUserBindingByWeChatId(wechatuser);
    		MmtService sms = new MmtService("");
    		MmtService mmt = new MmtService();
    		if(userBind != null){
    			logger.warn("grant userBind="+ userBind);
        		RespGrantTicket ticket = mmt.grantTicket(userBind.getPhone());
        		
        		if(ticket!=null){
        			TicketGrant tg= ticket.getTickets().get(0);
        			if(tg != null){
        				//String smsStr = String.format(WeChatConstant.GIVEN_COUPON_MSG, tg.getTicketName(),tg.getTicketNo());
            			String smsStr =  MessageFormat.format(WeChatConstant.GIVEN_COUPON_MSG, tg.getTicketNo());
            			sms.sendSms(userBind.getPhone(), smsStr);
            			model.addAttribute("code","成功");
            			model.addAttribute("reason",smsStr);
        			}
        		}
        		else {
        			model.addAttribute("code","失败");
        			model.addAttribute("reason","发券失败。");
				}
    		}
    		else {
    			model.addAttribute("code","失败");
    			model.addAttribute("reason","您还未成为绑定用户。");
			}
    	}
    	
    	return "wechat/message";
    }
   
    //用户绑定
    @RequestMapping(value="/wechat/mobile/",method=RequestMethod.GET)
    public String moblie(SitePreference sitePreference, Device device, Model model,HttpServletRequest request){
    	 logger.info("SitePreference : " + sitePreference);
         logger.info("Device : " + device);
         String wechatuser = request.getParameter("wechatuser");
         model.addAttribute("message", "Hello World!");
         model.addAttribute("wechatuser",wechatuser);
         return "wechat/mobile";
    }
    //gomodify
    @RequestMapping(value="/wechat/gomodify")
    public String goModify(Model model){
    	return "wechat/modify";
    }
    
    //用户注册
    @RequestMapping(value="/wechat/register")
    public String register(Model model, HttpServletRequest request, HttpServletResponse response){
    	String wechatuser = (String)request.getParameter("wechatuser");
    	logger.debug("wechat user is ："+ wechatuser);
    	model.addAttribute("wechatuser",wechatuser);
    	return "wechat/register";
    }
    
    //公司介绍
    @RequestMapping(value="/wechat/intro")
    public String companyIntro(Model model, HttpServletRequest request, HttpServletResponse response){
    	String wechatuser = (String)request.getParameter("wechatuser");
    	model.addAttribute("wechatuser",wechatuser);
    	return "company/intro";
    }
    
    //门店
    @RequestMapping(value="/wechat/storelist")
    public String storeList(Model model, HttpServletRequest request, HttpServletResponse response){
    	String wechatuser = (String)request.getParameter("wechatuser");
    	List<String> strList = StoreArea.getAllCity();
    	String cityName = request.getParameter("cityName");
    	byte bb[]; 
        try {
			bb = cityName.getBytes("ISO-8859-1");//以"ISO-8859-1"方式解析name字符串 
			cityName= new String(bb, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} 
        
    	if(Strings.isNullOrEmpty(cityName)){
    		cityName = WeChatConstant.DEFAULT_CITY;
    	}
    	List<Store> storeList = StoreArea.getStoresOneCity(cityName);
    	
    	model.addAttribute("city",cityName);
    	model.addAttribute("strList",strList);
    	model.addAttribute("storeList",storeList);
    	model.addAttribute("wechatuser",wechatuser);
    	return "company/storelist";
    }
    
    //公司介绍--新
    @RequestMapping(value="/wechat/company")
    public String com(Model model, HttpServletRequest request, HttpServletResponse response){
    	String wechatuser = (String)request.getParameter("wechatuser");
    	List<Prod> list = Prod.getTopNProds();
    	model.addAttribute("topnProd",list);
    	model.addAttribute("wechatuser",wechatuser);
    	return "company/com";
    }
   
    //产品
    @RequestMapping(value="/wechat/intro1")
    public String companyIntro1(Model model, HttpServletRequest request, HttpServletResponse response){
    	String wechatuser = (String)request.getParameter("wechatuser");
    	String prodId = request.getParameter("prod");
    	String catId = request.getParameter("catId");
    	List<Catalog> cat = Catalog.getAllCatalogOrder();
    	List<Prod> prodList = Prod.getProdsByCatId(new Integer(catId));
    	if(prodList == null || prodList.size()==0){
    		model.addAttribute("wechatuser",wechatuser);
        	model.addAttribute("cat",cat);
        	return "company/intro1";
    	}
    	
    	Prod prod = null;
    	if(Strings.isNullOrEmpty(prodId)){
    		prod = prodList.get(0);
    		prodList.remove(0);
    	}
    	else {
    		int i = 0;
			for (Prod p : prodList) {
				if(p.getId() == new Integer(prodId).intValue()){
					prod = p;
					prodList.remove(i);
					break;
				}
				i++;
			}
		}
    	
    	model.addAttribute("prod",prod);
    	model.addAttribute("prodList",prodList);
    	
    	model.addAttribute("wechatuser",wechatuser);
    	model.addAttribute("cat",cat);
    	return "company/intro1";
    }
    
    //文章
    @RequestMapping(value="/wechat/article")
    public String showArticle(Model model, HttpServletRequest request, HttpServletResponse response){
    	String id = (String)request.getParameter("id");
    	Article article = Article.findArticle(new Integer(id));
    	model.addAttribute("article",article);
    	return "article/show";
    }
    
    //最新信息
    public String lastestPromotion(Model model, HttpServletRequest request, HttpServletResponse response){
    	
    	return "wechat/promotion";
    }
    
    //查看门店详细信息
    @RequestMapping(value="/wechat/mobilestore/",method=RequestMethod.GET)
    public String moblieStoreDetail(SitePreference sitePreference, Device device, Model model,HttpServletRequest request){
    	int storeId = new Integer(request.getParameter("storeId"));
    	Store store = Store.findStore(storeId);
         model.addAttribute("store", store);
         model.addAttribute("basicPic",WeChatConstant.BASE_PIC_WEBSITE);
         return "wechat/mobilestore";
    }   
    
    //查看活动详细信息
    @RequestMapping(value="/wechat/mobilepro/",method=RequestMethod.GET)
    public String mobliePromotionDetail(SitePreference sitePreference, Device device, Model model, HttpServletRequest request){
    	 int proId = new Integer(request.getParameter("proId"));
    	 ProWechat pro = ProWechat.findProWechat(proId);
         model.addAttribute("pro", pro);
         return "wechat/mobilepro";
    }      
    //废掉
	public String getLocMsg(String lat,String lng,String userName){
		String returnXml = "";
		//StringBuffer replyMsg = new StringBuffer();
		BaiduMapService baidu = new BaiduMapService();
		String respXml;
		try {
			respXml = baidu.getPalace("银行", lat, lng);
			List<BaiduPlaceResponse> list = BaiduPlaceResponse.getBaiduPlace(respXml);
			returnXml =WeChatReplyNewsMessage.getWeChatReplyNewsMessageByBaiduPlace(list,Double.valueOf(lat),Double.valueOf(lng),userName,WeChatConstant.ARTICLE_SIZE);
		} catch (Exception e) {
			logger.warn(e.getMessage());
		}
		return returnXml;
	}
	
	private String getStores(String lat,String lng,String userName){
		List<Store> storeList = Store.findAllStores();
		/*
		 * 1.计算所有门店和目标之间的距离。
		 * 2.放进一个Map，key为距离，value为List中的index
		 * 3.
		 */
		TreeMap<Double, Integer> treeMap = new TreeMap<Double, Integer>();
		for(int i=0;i<storeList.size();i++){
			Store store = storeList.get(i);
			Double distance = GeoUtil.DistanceOfTwoPoints(Double.valueOf(store.getStoreLnt()), Double.valueOf(store.getStoreLat()), new Double(lng), new Double(lat), GaussSphere.Beijing54);
			treeMap.put(distance, i);
		}
		
		String returnXml = WeChatReplyNewsMessage.getSotreWeChatReplyNewsMessage(treeMap,storeList, new Double(lat), new Double(lng), userName, WeChatConstant.STORE_SIZE);
		return returnXml;
	}

	private String getProWeChat(List<ProWechat> proList,String key,String userName){
		//List<ProWechat> proList = ProWechat.findProWechatsByNameAndDesc(key);
		String returnXml = WeChatReplyNewsMessage.getProWeChat(proList,userName,WeChatConstant.PRO_WECHAT_SIZE);
		return returnXml;
	}
	
	private WeChatTextMessage getWeChatTextMessage(String xml){
		XStream xstream = new XStream(new DomDriver());
		xstream.alias("xml", WeChatTextMessage.class);
		xstream.aliasField("ToUserName", WeChatTextMessage.class, "toUserName");
		xstream.aliasField("FromUserName", WeChatTextMessage.class, "fromUserName");
		xstream.aliasField("CreateTime", WeChatTextMessage.class, "createTime");
		xstream.aliasField("MsgType", WeChatTextMessage.class, "messageType");
		xstream.aliasField("Content", WeChatTextMessage.class, "content");
		xstream.aliasField("MsgId", WeChatTextMessage.class, "msgId");
		WeChatTextMessage wechatTextMessage = (WeChatTextMessage)xstream.fromXML(xml); 
		return wechatTextMessage;
	}
	
	private WeChatEventMessage getWeChatEventMessage(String xml){
		XStream xstream = new XStream(new DomDriver());
		xstream.alias("xml", WeChatEventMessage.class);
		xstream.aliasField("ToUserName", WeChatEventMessage.class, "toUserName");
		xstream.aliasField("FromUserName", WeChatEventMessage.class, "fromUserName");
		xstream.aliasField("CreateTime", WeChatEventMessage.class, "createTime");
		xstream.aliasField("MsgType", WeChatEventMessage.class, "msgType");
		xstream.aliasField("Event", WeChatEventMessage.class, "event");
		xstream.aliasField("EventKey", WeChatEventMessage.class, "eventKey");
		WeChatEventMessage weChatEventMessage = (WeChatEventMessage)xstream.fromXML(xml); 
		return weChatEventMessage;
	}
	
	private String getReplyTextMessage(String content, String weChatUser){
		WeChatReplyTextMessage we = new WeChatReplyTextMessage();
		we.setMessageType("text");
		we.setFuncFlag("0");
		we.setCreateTime(new Long(new Date().getTime()).toString());
		we.setContent(content);
		we.setToUserName(weChatUser);
		we.setFromUserName(WeChatConstant.FROMUSERNAME);
		XStream xstream = new XStream(new DomDriver()); 
		xstream.alias("xml", WeChatReplyTextMessage.class);
		xstream.aliasField("ToUserName", WeChatReplyTextMessage.class, "toUserName");
		xstream.aliasField("FromUserName", WeChatReplyTextMessage.class, "fromUserName");
		xstream.aliasField("CreateTime", WeChatReplyTextMessage.class, "createTime");
		xstream.aliasField("MsgType", WeChatReplyTextMessage.class, "messageType");
		xstream.aliasField("Content", WeChatReplyTextMessage.class, "content");
		xstream.aliasField("FuncFlag", WeChatReplyTextMessage.class, "funcFlag");
		String xml =xstream.toXML(we);
		return xml;
	}
}
